<?php

namespace app\api\controller\v1;

use app\common\exception\Client;
use think\Request;
use app\api\validate\User as UserValidate;
use app\common\service\User as UserService;
use think\response\Json;

class Token
{

    /**
     * 微信小程序登录
     * @param Request $request
     * @return Json
     * @throws Client
     */
    public function getToken(Request $request): Json
    {

        // 验证参数
        $params = $request->only(['code']);
        $validate = new UserValidate();
        if(!$validate->check($params)){
            throw new Client(220001,$validate->getError());
        }
        // 调用服务层
        $service = new UserService();
        $token = $service->getToken($params['code']);

        return writeJson(200,$token,'登录成功');
    }

    /**
     * @param Request $request
     * @return void
     * @throws Client
     */
    public function verify(Request $request): Json
    {
        $params = $request->only(['token']);
        $uid = (new UserService())->getUserIdFromToken($params['token']);
        if($uid)return writeJson(200,['is_valid'=>true],'登录成功');
    }
}